package com.example.cmh.service.impl;

import com.example.cmh.common.JwtUtils;
import com.example.cmh.mapper.UserMapper;
import com.example.cmh.pojo.User;
import com.example.cmh.service.UserService;
import com.example.cmh.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private com.example.cmh.mapper.DepartmentMapper departmentMapper;
    
    @Autowired
    private com.example.cmh.mapper.PositionMapper positionMapper;
    
    @Override
    public Map<String, Object> getUsers(Integer page, Integer size, String userName, String userPhone, String startTime, String endTime, String userStatus) {
        // 计算偏移量
        int offset = (page - 1) * size;
        
        // 获取用户列表
        List<User> users = userMapper.getUsers(offset, size, userName, userPhone, startTime, endTime, userStatus);
        
        // 获取总数
        Integer total = userMapper.getUsersCount(userName, userPhone, startTime, endTime, userStatus);
        
        // 构建分页结果
        Map<String, Object> result = new HashMap<>();
        result.put("list", users);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("pages", (total + size - 1) / size);
        
        return result;
    }
    
    @Override
    public Map<String, Object> getUsersByUserId(Integer page, Integer size, Integer userId) {
        // 计算偏移量
        int offset = (page - 1) * size;
        
        // 获取用户列表
        List<User> users = userMapper.getUsersByUserId(offset, size, userId);
        
        // 获取总数
        Integer total = userMapper.getUsersByUserIdCount(userId);
        
        // 构建分页结果
        Map<String, Object> result = new HashMap<>();
        result.put("list", users);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("pages", (total + size - 1) / size);
        
        return result;
    }
    
    @Override
    public Map<String, Object> getUsersByDepartmentId(Integer page, Integer size, Integer departmentId) {
        // 计算偏移量
        int offset = (page - 1) * size;
        
        // 获取用户列表
        List<User> users = userMapper.getUsersByDepartmentId(offset, size, departmentId);
        
        // 获取总数
        Integer total = userMapper.getUsersByDepartmentIdCount(departmentId);
        
        // 构建分页结果
        Map<String, Object> result = new HashMap<>();
        result.put("list", users);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("pages", (total + size - 1) / size);
        
        return result;
    }
    
    @Override
    public void addUsers(User user) {
        // 设置默认值
        if (user.getGender() == null) {
            user.setGender(0);
        }
        if (user.getUserType() == null) {
            user.setUserType(0);
        }
        if (user.getUserStatus() == null) {
            user.setUserStatus(0);
        }
        if (user.getRegisterTime() == null) {
            user.setRegisterTime(new Date());
        }
        
        // 密码加密
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            String encryptedPassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
            user.setPassword(encryptedPassword);
        }
        
        userMapper.addUsers(user);
    }
    
    @Override
    public void updateUser(User user) {
        // 如果更新密码，需要加密
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            String encryptedPassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
            user.setPassword(encryptedPassword);
        }
        
        userMapper.updateUser(user);
    }
    
    @Override
    public void deleteUser(Integer userId) {
        userMapper.deleteUser(userId);
    }
    
    @Override
    public UserVO login(Map<String, String> loginRequest) {
        String userName = loginRequest.get("userName");
        String password = loginRequest.get("password");
        
        // 参数校验
        if (userName == null || userName.isEmpty() || password == null || password.isEmpty()) {
            throw new RuntimeException("用户名或密码为空");
        }
        
        // 密码加密
        String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        
        // 查询用户
        User user = userMapper.login(userName, encryptedPassword);
        
        if (user == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 检查用户状态
        if (user.getUserStatus() != null && user.getUserStatus() == 1) {
            throw new RuntimeException("用户已被停用");
        }
        
        // 生成JWT令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getUserId());
        claims.put("userName", user.getUserName());
        claims.put("userType", user.getUserType());
        
        String token = JwtUtils.generateJwt(claims);
        user.setToken(token);
        
        // 更新用户token
        userMapper.updateUserToken(user.getUserId(), token);

        // 查询部门名称
        String departmentName = null;
        if (user.getDepartmentId() != null) {
            var dept = departmentMapper.getDepartmentsById(user.getDepartmentId());
            if (dept != null) departmentName = dept.getDepartmentName();
        }
        // 查询岗位名称
        String positionName = null;
        if (user.getPositionId() != null) {
            var pos = positionMapper.getPositionById(user.getPositionId());
            if (pos != null) positionName = pos.getPositionName();
        }

        // 封装VO
        UserVO userVO = new UserVO();
        org.springframework.beans.BeanUtils.copyProperties(user, userVO);
        userVO.setDepartmentName(departmentName);
        userVO.setPositionName(positionName);

        return userVO;
    }
    
    @Override
    public void logout(Integer userId) {
        userMapper.updateUserToken(userId, null);
    }
    
    @Override
    public java.util.Map<String, Object> getUsersByDepartmentIds(Integer page, Integer size, java.util.List<Integer> departmentIds) {
        int offset = (page - 1) * size;
        java.util.List<User> users = userMapper.getUsersByDepartmentIds(offset, size, departmentIds);
        Integer total = userMapper.getUsersByDepartmentIdsCount(departmentIds);
        java.util.Map<String, Object> result = new java.util.HashMap<>();
        result.put("list", users);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("pages", (total + size - 1) / size);
        return result;
    }
    
    @Override
    public com.example.cmh.vo.UserVO updateOwnUser(Integer userId, User user) {
        // 只允许更新昵称、手机号、邮箱、性别
        User updateUser = new User();
        updateUser.setUserId(userId);
        updateUser.setUserNickname(user.getUserNickname());
        updateUser.setUserPhone(user.getUserPhone());
        updateUser.setUserEmail(user.getUserEmail());
        updateUser.setGender(user.getGender());
        userMapper.updateUser(updateUser);
        // 查询并返回最新信息
        User latest = userMapper.getUsersByUserId(0, 1, userId).get(0);
        // 查询部门名称
        String departmentName = null;
        if (latest.getDepartmentId() != null) {
            var dept = departmentMapper.getDepartmentsById(latest.getDepartmentId());
            if (dept != null) departmentName = dept.getDepartmentName();
        }
        // 查询岗位名称
        String positionName = null;
        if (latest.getPositionId() != null) {
            var pos = positionMapper.getPositionById(latest.getPositionId());
            if (pos != null) positionName = pos.getPositionName();
        }
        // 封装VO
        com.example.cmh.vo.UserVO userVO = new com.example.cmh.vo.UserVO();
        org.springframework.beans.BeanUtils.copyProperties(latest, userVO);
        userVO.setDepartmentName(departmentName);
        userVO.setPositionName(positionName);
        return userVO;
    }
    
    @Override
    public void updatePassword(Integer userId, String oldPassword, String newPassword) {
        // 查询用户
        User user = userMapper.getUsersByUserId(0, 1, userId).get(0);
        // 校验旧密码
        String encryptedOld = org.springframework.util.DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        if (!encryptedOld.equals(user.getPassword())) {
            throw new RuntimeException("旧密码错误");
        }
        // 更新新密码
        String encryptedNew = org.springframework.util.DigestUtils.md5DigestAsHex(newPassword.getBytes());
        User updateUser = new User();
        updateUser.setUserId(userId);
        updateUser.setPassword(encryptedNew);
        userMapper.updateUser(updateUser);
    }
    
    @Override
    public User getUserByName(String userName) {
        return userMapper.getUserByName(userName);
    }
} 